/**
 * @description  : 字典多选
 * @descriptionDetail : 字典多选
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-10-03 17:09:22
 */
<template>
  <view style="width: 100%;">
    <!-- 非弹窗显示 -->
    <view v-if="!popup">
      <u-checkbox-group v-bind="$attrs" v-model="mVal" @change="checkboxGroupChange">
        <u-checkbox
          :name="item.value"
          v-for="(item, index) in dictList"
          :key="index" 
          v-model="item.checked"
          @change="handleChange"
        >
          {{ item.label }}
        </u-checkbox>
      </u-checkbox-group>
    </view>
    <!-- 弹窗显示 -->
    <view v-else>
      <u-input
        :border="false"
        type="select"
        :placeholder="$attrs.placeholder || '请选择'"
        v-model="value"
        v-bind="$attrs"
        @click="dictShow = true"
        :select-open="dictShow"
      ></u-input>
      <u-popup mode="bottom" height="60%" border-radius="16" v-model="dictShow" @touchmove.prevent>
        <multi-select :options="dictOptions" @select="handleSelect"></multi-select>
      </u-popup>
    </view>
  </view>
</template>
<script>
import MultiSelect from "./multi-select.vue"
export default {
  components: {MultiSelect},
  props: {
    value: {
      type: String | Number,
      default: ''
    },
    popup: {    // 是否弹窗选择
      type: Boolean,
      default: false,
    },
    dictType: {     // 字典类型
      type: String,
      default: ""
    },
  },
  data() {
    return {
      mVal: this.value,
      dictList: [],
      dictShow: false,
      dictOptions: [],
    }
  },
  watch: {
    dictType: {
      immediate: true,
      handler(v) {
        this.dictList = this.$u.dic.getByDictCode(v);
        this.dictList.forEach(d => d.checked = this.mVal.includes(d.value));
        this.dictOptions = this.dictList.map(d => {
          d.uid = d.value;
          d.name = d.label;
          return d;
        });
      },
    },
    value: {
      immediate: true,
      handler(v) {
        if (typeof v === 'undefined') {
          return;
        }
        if (!Array.isArray(v)) {
          v = v.split(",");
        }
        this.mVal = v;
        // 修复动态赋值异常问题
        this.dictList.forEach(d => {
          d.checked = v.includes(d.value);
        });
      },
    }
  },
  methods: {
    checkboxGroupChange(args) {
      this.$emit("input", args.join(","));
    },
    handleChange(arg) {
      this.dictList.forEach(d => {
        d.value == arg.name && (d.checked = arg.value)
      });
      this.$forceUpdate();
    },
    // 多选弹窗选中确认
    handleSelect(items) {
      let name = items.map(it => it.name);
      let value = items.map(it => it.value);
      this.$emit("input", name.join(","));
      this.$emit("confirm", {name: name.join(","), value: value.join(",")});
      this.dictShow = false;
    }
  },
}
</script>